package com.wxxymaker.edu.hook;

import com.blade.mvc.RouteContext;
import com.blade.mvc.WebContext;
import com.blade.mvc.hook.WebHook;
import com.wxxymaker.edu.model.entity.Course;
import com.wxxymaker.edu.model.entity.User;
import com.wxxymaker.edu.service.CourseService;
import com.wxxymaker.edu.utils.HttpUtil;
import com.wxxymaker.edu.utils.TokenUtils;

/**
 * @AUTHOR soft
 * @DATE 2018/9/8 11:04
 * @DESCRIBE 课程设置拦截器
 * 保证设置的课程存在且属于当前登录教师的
 * 同时将课程id传入请求域
 * kid: 课程id
 */
public class CourseSetHook implements WebHook {

    @Override
    public boolean before(RouteContext ctx) {
        String uri  = ctx.uri();
        User   user = TokenUtils.currentUser();
        if (uri.startsWith("/course/set/") && !uri.contains("newCourse")) {
            Integer kid = ctx.pathInt("kid");
            ctx.attribute("kid", kid); // 把课程id放入request域
//            if (user.getRole() >= 3) return true; // 超级管理直接放行
            if (kid != null && kid != 0) {
                CourseService service = WebContext.blade().ioc().getBean(CourseService.class);
                Course course = service.byId(kid);
                if (course == null || !user.getId().equals(course.getUserId())) {
                    ctx.render(HttpUtil._400());
                    return false;
                }
            }
        }
        return true;
    }
}
